package com.lujianfei.productprice.ui.order;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class OrderModel implements OrderContract.Model {
    List<OrderEntity> data = null;
    double totalPrice = 0;
    @Override
    public List<OrderEntity> loadData() {
        data = OrderEntity.listAll(OrderEntity.class,"createTime desc");
        if (null!=data){
            totalPrice = 0;
            for (OrderEntity orderEntity:
            data) {
                Set<Long> shopIds = new HashSet<>();
                List<OrderDetailEntity> orderDetailEntities = OrderDetailEntity.find(OrderDetailEntity.class, "orderId=?", new String[]{""+orderEntity.getId()},null,"shopId asc",null);
                for (OrderDetailEntity orderDetailEntity:
                     orderDetailEntities) {
                    if (!shopIds.contains(orderDetailEntity.getShopId())){
                        orderDetailEntity.setShowShopName(true);
                        shopIds.add(orderDetailEntity.getShopId());
                    }else{
                        orderDetailEntity.setShowShopName(false);
                    }
                }
                orderEntity.setOrderDetailEntityList(orderDetailEntities);
                totalPrice += orderEntity.getTotalPrice();
            }
        }
        return data;
    }

    @Override
    public void delete(OrderEntity itemAtPosition) {
        if (null!=itemAtPosition.getOrderDetailEntityList()){
            for (OrderDetailEntity orderDetailEntity:
            itemAtPosition.getOrderDetailEntityList()) {
                orderDetailEntity.delete();
            }
        }
        itemAtPosition.delete();
    }

    @Override
    public double getTotalPrice() {
        return totalPrice;
    }
}
